<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //统计一个数组中有多少个不重复的单词：
        // 不用reduce时： 
        var arr = ["apple", "orange", "apple", "orange", "pear", "orange"];

        function getWordCnt() {
            var obj = {};
            for (var i = 0, l = arr.length; i < l; i++) {
                var item = arr[i];
                obj[item] = (obj[item] + 1) || 1;
            }
            return obj;
        }
        console.log(getWordCnt()); //{apple: 2, orange: 3, pear: 1}


        //3..
        // var arr = [1, 1, 2, 3];
        var newArr = [...new Set(arr)]; // 对原始数组去重
        var list = [];
        newArr.forEach(i => {
            list.push(arr.filter(t => t === i))
        })
        var mlist = [];
        list.forEach((i, index) => {
            mlist.push({
                name: newArr[index],
                num: i.length,
            })
        })
        console.log(list, mlist)


        // 用reduce时： 
        var arr = ["apple", "orange", "apple", "orange", "pear", "orange"];

        function getWordCnt() {
            return arr.reduce(function (prev, next) {
                prev[next] = (prev[next] + 1) || 1;
                return prev;
            }, {});
        }
        console.log(getWordCnt()); //{apple: 2, orange: 3, pear: 1}
    </script>
</body>

</html>